package com.anzym.android.kegdroidkey;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.anzym.android.kegdroidkey.R;
import com.anzym.android.kegdroidlibrary.database.BeerDataSource;
import com.anzym.android.kegdroidlibrary.models.Beer;
import com.anzym.android.kegdroidlibrary.models.KegDroid;

import java.text.DecimalFormat;
import java.util.ArrayList;

public class KegDroidListAdapter extends BaseAdapter {
    
    private static final String TAG = KegDroidListAdapter.class.getSimpleName();
    
    private String distanceResult;
    private String bearingResult;
    private double bearing;
    private Activity activity;
    private KegDroidKeyActivity ctx;
    private ArrayList<KegDroid> kegdroids;  
    private static LayoutInflater inflater = null;
    LocationManager locManager;
    private final DecimalFormat dFormatter = new DecimalFormat("#.##");
    private final DecimalFormat bFormatter = new DecimalFormat("###" + (char) 0x00B0);
    
    public KegDroidListAdapter (Context ctx, ArrayList<KegDroid> k) {
        this.ctx = (KegDroidKeyActivity) ctx;
        this.kegdroids = k;
        this.inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.locManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    public int getCount() {
        return kegdroids.size();
    }

    @Override
    public Object getItem(int position) {
        return kegdroids.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
    
    public class ViewHolder {
        private TextView kdName;
        private TextView kdBearing;
        private TextView kdDistance;
        private ImageView kdBearingArrow;
        
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null){
            convertView = inflater.inflate(R.layout.kegdroid_item, null);
            holder = new ViewHolder();
            holder.kdName = (TextView) convertView.findViewById(R.id.kegdroid_name);
            holder.kdBearing = (TextView) convertView.findViewById(R.id.bearing_text);
            holder.kdDistance = (TextView) convertView.findViewById(R.id.distance_text);
            holder.kdBearingArrow = (ImageView) convertView.findViewById(R.id.bearing_pointer);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }
        KegDroid kd = kegdroids.get(position);
        holder.kdName.setText(kd.getName());
        setBearingDistance(kd);
        holder.kdDistance.setText(distanceResult);
        holder.kdBearing.setText(bearingResult);
        Matrix matrix = new Matrix();
        matrix.postRotate((float) rad2deg(bearing));
        Bitmap bMap = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.arrow);
        int bmpWidth = bMap.getWidth();
        int bmpHeight = bMap.getHeight();
        Bitmap rotatedBMap = Bitmap.createBitmap(bMap, 0,0,bmpWidth, bmpHeight, matrix, true);
        holder.kdBearingArrow.setImageBitmap(rotatedBMap);
        
        return convertView;
    }
    
    public void setBearingDistance(KegDroid k) {
        double distance = 0;
        int EARTH_RADIUS = 6371;
        int FEET_PER_MILE = 5280;
        double myLat = 0;
        double myLon = 0;
        
        Location location = locManager.getLastKnownLocation(
                LocationManager.NETWORK_PROVIDER);
        if (location != null) {
            myLat = location.getLatitude();
            myLon =location.getLongitude();
        }
        else {
            Log.e(TAG, "location was NULL!");
        }
        
        double dLat = deg2rad(k.getLat() - myLat);
        double dLon = deg2rad(k.getLon() - myLon);
        
        double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.cos(deg2rad(k.getLat())) * Math.cos(deg2rad(myLat)) *
                Math.sin(dLon/2) * Math.sin(dLon/2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        distance = EARTH_RADIUS * c;  //distance in km
        distance *= .621371; //convert miles
        distanceResult = null;
        if (distance < .25) {
            distanceResult = dFormatter.format(distance * FEET_PER_MILE);
            distanceResult += " ft";
        } else {
            distanceResult = dFormatter.format(distance);
            distanceResult += " mi";
        }
        
        double y = Math.sin(dLon) * Math.cos(k.getLat());
        double x = Math.cos(k.getLat()) * Math.sin(myLat) -
                Math.sin(k.getLat()) * Math.cos(myLat) *  Math.cos(dLon);
        bearing = Math.atan2(y,x);
        bearingResult = null;
        bearingResult = bFormatter.format(convertToBearing(rad2deg(bearing)));

    }
    
    public double convertToBearing(double deg) {
        return (deg+360) % 360;
    }
    
    public double deg2rad(double deg) {
        return deg * (Math.PI/180);
    }
    public double rad2deg(double rad) {
        return rad * (180/Math.PI);
    }
}
